/**
 * Created by Administrator on 2017/7/6 0006.
 */
var utils = {};
var fs = require('fs');
var qr = require('qr-image');
var images = require('images');
var lut = './public/qrcode/';
var disLut = './public/distribution/disQR/';
var shareUrl = 'http://weblogin.178dn.net/view/minWheel.html?regChannel=';
var diShareUrl = 'http://weblogin.178dn.net/distribution/view/me.html?regChannel=';
/**
 * turnplate
 * 根据地址生成二维码
 * 参数 url(string) 地址
 * 参数 callback(Function)
 */
utils.createQr = function(sid,openid,regChannel,callback){
    var url = shareUrl+regChannel+'&referee='+openid+'&sid='+sid;
    //console.log('shareUrl:%s',url);
    var qr_png = qr.image(url, { type: 'png',size : 7 });
    var imgName = lut+sid+'.png';
    var qr_pipe = qr_png.pipe(fs.createWriteStream(imgName));
    qr_pipe.on('error', function(err){
        console.log(err);
        callback(1,null);
        return;
    });
    qr_pipe.on('finish', function(){
        comPicture(imgName, function (qrimage) {
            callback(null,1);
        });
    });
};


var comPicture = function(qrimage,cb){
    images(lut+"baseImg.jpg")                     //Load image from file 原图
    //加载图像文件
        .size(640)                          //Geometric scaling the image to 400 pixels width
        //等比缩放图像到400像素宽
        .draw(images(qrimage), 145, 470)   //Drawn logo at coordinates (10,10)
        //在(10,10)处绘制Logo
        .save(qrimage, {               //Save the image to a file,whih quality 50
            quality : 50                    //保存图片到文件,图片质量为50
        });
    cb(qrimage)
};

/**
 * distribution
 * 根据地址生成二维码
 * 参数 url(string) 地址
 * 参数 callback(Function)
 */
utils.createDisQR = function(uid,openid,regChannel,callback){
    var url = diShareUrl+regChannel+'&referee='+openid+'&uid='+uid;
    //console.log('shareUrl:%s',url);
    var qr_png = qr.image(url, { type: 'png',size : 3 });
    var imgName = disLut+uid+'.png';
    var qr_pipe = qr_png.pipe(fs.createWriteStream(imgName));
    qr_pipe.on('error', function(err){
        console.log(err);
        callback(1,null);
        return;
    });
    qr_pipe.on('finish', function(){
        callback(null,1);
        //disPicture(imgName, function (qrimage) {
        //    callback(null,200);
        //});
    });
};


var disPicture = function(qrimage,cb){
    images(disLut+"baseImg.jpg")                     //Load image from file 原图
    //加载图像文件
        .size(400)                          //Geometric scaling the image to 400 pixels width
        //等比缩放图像到400像素宽
        .draw(images(qrimage), 125, 240)   //Drawn logo at coordinates (10,10)
        //在(10,10)处绘制Logo
        .save(qrimage, {               //Save the image to a file,whih quality 50
            quality : 80                    //保存图片到文件,图片质量为50
        });
    cb(qrimage)
};

module.exports = utils;